package com.sftz.modules.admin.authority.user.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;

import com.sftz.framework.res.entities.SFunctionEntity;
import com.sftz.framework.res.entities.SRoleEntity;
import com.sftz.framework.res.entities.SUserEntity;
import com.sftz.framework.res.entities.SUserRoleMapEntity;
import com.sftz.framework.res.enums.UserStatusEnum;
import com.sftz.framework.res.enums.UserTypeEnum;
import com.sftz.modules.admin.authority.user.form.UserModForm;
import com.sftz.modules.admin.authority.user.service.UserService;
import com.uxuexi.core.common.util.EnumUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.util.DbSqlUtil;
import com.uxuexi.core.web.base.service.BaseService;
import com.uxuexi.core.web.util.FormUtil;

@IocBean(name = "userService")
public class UserServiceImpl extends BaseService<SUserEntity> implements UserService {

	@Override
	public boolean update(UserModForm form) {
		//修改用户实体
		FormUtil.modify(dbDao, form, SUserEntity.class);

		//更新用户的角色
		updateSUserRoleMapEntity(form);
		return true;
	}

	@Override
	public Map<String, Object> findUser(long userId) {
		Map<String, Object> obj = new HashMap<String, Object>();

		//全部角色
		List<SRoleEntity> allRole = dbDao.query(SRoleEntity.class, null, null);

		//根据用户查询user_role
		List<SUserRoleMapEntity> relation = dbDao.query(SUserRoleMapEntity.class, Cnd.where("userId", "=", userId),
				null);

		//如果该用户拥有功能
		if (!Util.isEmpty(relation)) {
			//该角色的功能id集合
			List<Integer> existsRoleIds = new ArrayList<Integer>();
			for (SUserRoleMapEntity r : relation) {
				existsRoleIds.add(r.getRoleId());
			}

			for (SRoleEntity role : allRole) {
				if (existsRoleIds.contains(role.getId())) {
					role.setChecked(true);
				} else {
					role.setChecked(false);
				}
			}
		}
		obj.put("roleList", allRole); //所有角色
		obj.put("user", dbDao.fetch(SUserEntity.class, userId)); //用户实体
		obj.put("userTypeEnum", EnumUtil.enum2(UserTypeEnum.class));//用户类型
		obj.put("userStatusEnum", EnumUtil.enum2(UserStatusEnum.class)); //用户状态
		return obj;
	}

	/**更新用户的角色*/
	public void updateSUserRoleMapEntity(UserModForm userForm) {
		List<SUserRoleMapEntity> mapList = userForm.getMap();

		Integer userId = Integer.parseInt(userForm.getId() + "");
		//根据用户查询用户角色关系
		List<SUserRoleMapEntity> before = dbDao.query(SUserRoleMapEntity.class, Cnd.where("userId", "=", userId), null);

		if (!Util.isEmpty(mapList)) {
			for (SUserRoleMapEntity map : mapList) {
				//角色id为空则不处理
				if (Util.isEmpty(map.getRoleId())) {
					continue;
				}
				map.setUserId(userId);
			}
		}
		dbDao.updateRelations(before, mapList);
	}

	@Override
	public SUserEntity findUser(String userName, String passwd) {
		return dbDao.fetch(SUserEntity.class, Cnd.where("userName", "=", userName).and("password", "=", passwd));
	}

	@Override
	public List<SFunctionEntity> findUserFunctions(long userId) {
		Sql sql = Sqls.create(sqlManager.get("admin_user_function_all"));
		sql.params().set("userId", userId);
		return DbSqlUtil.query(dbDao, SFunctionEntity.class, sql, null);
	}

	@Override
	public SUserEntity findByTel(String tel) {
		return dbDao.fetch(SUserEntity.class, Cnd.where("tel", "=", tel));
	}

	@Override
	public SUserEntity findUserById(long userId) {
		return dbDao.fetch(SUserEntity.class, Cnd.where("id", "=", userId));
	}

	@Override
	public boolean updateAvatar(long userId, String avatar) {
		dbDao.update(SUserEntity.class, Chain.make("avatar", avatar), Cnd.where("id", "=", userId));
		return true;
	}

	/**
	 * 根据手机号查询用户是否存在
	 * @param tel  手机号
	 */
	@Override
	public int findUserCount(String tel) {
		Sql sql = Sqls.create(sqlManager.get("admin_s_user_count_by_tel"));
		sql.params().set("tel", tel);
		return DbSqlUtil.fetchInt(dbDao, sql);
	}

}
